package com.atguigu.day09;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Session;
import org.apache.flink.table.api.Slide;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.Tumble;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.*;

public class Flink16_TableAPI_GroupWindow {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env
                .fromElements(new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 6000L, 60))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((element, recordTimestamp) -> element.getTs())
                );

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        Table table = tableEnv
//                .fromDataStream(waterSensorStream, $("id"), $("ts").rowtime(), $("vc"));
                .fromDataStream(waterSensorStream, $("id"), $("ts"), $("vc"),$("pt").proctime());

        //TODO 使用GroupWindow
        table
                //基于事件时间的滚动窗口，窗口大小为3s
//                .window(Tumble.over(lit(3).seconds()).on($("ts")).as("w"))
                //滑动窗口
//                .window(Slide.over(lit(3).seconds()).every(lit(2).second()).on($("ts")).as("w"))
                //会话窗口
//                .window(Session.withGap(lit(2).second()).on($("ts")).as("w"))
                //基于元素个数的滚动窗口 一定要指定时间字段 并且必须是处理时间字段
                .window(Tumble.over(rowInterval(2L)).on($("pt")).as("w"))
                .groupBy($("id"), $("w"))
//                .select($("id"), $("vc").sum(), $("w").start().as("Wstart"), $("w").end().as("Wend"))
                .select($("id"), $("vc").sum())
                .execute()
                .print();


    }
}
